package com.warehouse.module.business.service.cargofile;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.warehouse.module.business.controller.admin.cargoinfo.vo.*;
import com.warehouse.module.business.enums.FileTypes;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

import com.warehouse.module.business.controller.admin.cargofile.vo.*;
import com.warehouse.module.business.dal.dataobject.cargofile.CargoFileDO;
import com.warehouse.framework.common.util.object.BeanUtils;

import com.warehouse.module.business.dal.mysql.cargofile.CargoFileMapper;

import static com.warehouse.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.warehouse.module.business.enums.ErrorCodeConstants.*;

/**
 * 货物资料附件 Service 实现类
 *
 * @author admin
 */
@Service
@Validated
public class CargoFileServiceImpl implements CargoFileService {

    @Resource
    private CargoFileMapper cargoFileMapper;

    /**
     * 订单新增/修改
     * @param createReqVO
     */
    @Transactional(rollbackFor = Exception.class)
    public void createUpdateOrder(CargoInfoSaveReqVO createReqVO){
        //申报文件
        {
            LambdaQueryWrapper<CargoFileDO> receiptQuery = Wrappers.lambdaQuery(CargoFileDO.class)
                    .eq(CargoFileDO::getCargoId, createReqVO.getId())
                    .eq(CargoFileDO::getFileType, FileTypes.SHENBAO_FILES.getCode());
            List<CargoFileDO> receiptFileList = cargoFileMapper.selectList(receiptQuery);
            changeFiles(createReqVO.getId(), createReqVO.getShenbaoFiles(), receiptFileList, FileTypes.SHENBAO_FILES.getCode());
        }
        //制单文件
        {
            LambdaQueryWrapper<CargoFileDO> receiptQuery = Wrappers.lambdaQuery(CargoFileDO.class)
                    .eq(CargoFileDO::getCargoId, createReqVO.getId())
                    .eq(CargoFileDO::getFileType, FileTypes.ZHIDAN_FILES.getCode());
            List<CargoFileDO> receiptFileList = cargoFileMapper.selectList(receiptQuery);
            changeFiles(createReqVO.getId(), createReqVO.getZhidanFiles(), receiptFileList, FileTypes.ZHIDAN_FILES.getCode());
        }
        //报关文件
        {
            LambdaQueryWrapper<CargoFileDO> receiptQuery = Wrappers.lambdaQuery(CargoFileDO.class)
                    .eq(CargoFileDO::getCargoId, createReqVO.getId())
                    .eq(CargoFileDO::getFileType, FileTypes.BAOGUAN_FILES.getCode());
            List<CargoFileDO> receiptFileList = cargoFileMapper.selectList(receiptQuery);
            changeFiles(createReqVO.getId(), createReqVO.getBaoguanFiles(), receiptFileList, FileTypes.BAOGUAN_FILES.getCode());
        }
        //鉴定报告
        {
            LambdaQueryWrapper<CargoFileDO> receiptQuery = Wrappers.lambdaQuery(CargoFileDO.class)
                    .eq(CargoFileDO::getCargoId, createReqVO.getId())
                    .eq(CargoFileDO::getFileType, FileTypes.JIANDING_FILES.getCode());
            List<CargoFileDO> receiptFileList = cargoFileMapper.selectList(receiptQuery);
            changeFiles(createReqVO.getId(), createReqVO.getJiandingFiles(), receiptFileList, FileTypes.JIANDING_FILES.getCode());
        }
        //DGD
        {
            LambdaQueryWrapper<CargoFileDO> receiptQuery = Wrappers.lambdaQuery(CargoFileDO.class)
                    .eq(CargoFileDO::getCargoId, createReqVO.getId())
                    .eq(CargoFileDO::getFileType, FileTypes.DGD_FILES.getCode());
            List<CargoFileDO> receiptFileList = cargoFileMapper.selectList(receiptQuery);
            changeFiles(createReqVO.getId(), createReqVO.getDgdFiles(), receiptFileList, FileTypes.DGD_FILES.getCode());
        }
    }

    private void changeFiles(Long cargoId, List<SimpleFileVO> uploadFiles, List<CargoFileDO> receiptFileList, Integer typeId){
        List<Long> delList = Lists.newArrayList();
        List<CargoFileDO> addList = Lists.newArrayList();
        Map<String, SimpleFileVO> fileMaps = Maps.newHashMap();
        if(CollUtil.isNotEmpty(uploadFiles)){
            fileMaps = uploadFiles.stream().collect(Collectors.toMap(SimpleFileVO::getId, it->it));
        }
        if(CollUtil.isNotEmpty(receiptFileList)){
            Map<String, CargoFileDO> fileMap = receiptFileList.stream().collect(Collectors.toMap(CargoFileDO::getFileId, it->it));
            if(CollUtil.isEmpty(fileMaps)){
                delList = receiptFileList.stream().map(CargoFileDO::getId).collect(Collectors.toList());
            }else{

                for(String key : fileMap.keySet()){
                    if(fileMaps.get(key) == null){
                        delList.add(fileMap.get(key).getId());
                    }else{
                        fileMaps.remove(key);
                    }
                }
            }
        }
        if(CollUtil.isNotEmpty(fileMaps)){
            for(SimpleFileVO fid : fileMaps.values()){
                CargoFileDO fileDo = new CargoFileDO();
                fileDo.setCargoId(cargoId);
                fileDo.setFileType(typeId);
                fileDo.setFileId(fid.getId());
                fileDo.setFileName(fid.getName());
                addList.add(fileDo);
            }
        }
        if(CollUtil.isNotEmpty(delList)){
            cargoFileMapper.deleteByIds(delList);
        }
        if(CollUtil.isNotEmpty(addList)){
            cargoFileMapper.insertBatch(addList);
        }
    }

    /**
     * 收货录入添加附件
     * @param receiptVO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void receiptInput(CargoReceiptVO receiptVO){
        //现场照片
        {
            LambdaQueryWrapper<CargoFileDO> receiptQuery = Wrappers.lambdaQuery(CargoFileDO.class)
                    .eq(CargoFileDO::getCargoId, receiptVO.getCargoId())
                    .eq(CargoFileDO::getFileType, FileTypes.RECEIPT_INPUT.getCode());
            List<CargoFileDO> receiptFileList = cargoFileMapper.selectList(receiptQuery);
            changeFiles(receiptVO.getCargoId(), receiptVO.getReceiptList(), receiptFileList, FileTypes.RECEIPT_INPUT.getCode());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void packGoods(CargoPackVO receiptVO){
        //收货现场照片
        {
            LambdaQueryWrapper<CargoFileDO> receiptQuery = Wrappers.lambdaQuery(CargoFileDO.class)
                    .eq(CargoFileDO::getCargoId, receiptVO.getCargoId())
                    .eq(CargoFileDO::getFileType, FileTypes.RECEIPT_INPUT.getCode());
            List<CargoFileDO> receiptFileList = cargoFileMapper.selectList(receiptQuery);
            changeFiles(receiptVO.getCargoId(), receiptVO.getReceiptList(), receiptFileList, FileTypes.RECEIPT_INPUT.getCode());
        }
        //货物包装照片
        {
            LambdaQueryWrapper<CargoFileDO> receiptQuery = Wrappers.lambdaQuery(CargoFileDO.class)
                    .eq(CargoFileDO::getCargoId, receiptVO.getCargoId())
                    .eq(CargoFileDO::getFileType, FileTypes.PACKAGE_GOODSS.getCode());
            List<CargoFileDO> receiptFileList = cargoFileMapper.selectList(receiptQuery);
            changeFiles(receiptVO.getCargoId(), receiptVO.getPackList(), receiptFileList, FileTypes.PACKAGE_GOODSS.getCode());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void shipmentGoods(CargoShipmentVO shipmentVO){
        //现场照片
        {
            LambdaQueryWrapper<CargoFileDO> receiptQuery = Wrappers.lambdaQuery(CargoFileDO.class)
                    .eq(CargoFileDO::getCargoId, shipmentVO.getCargoId())
                    .eq(CargoFileDO::getFileType, FileTypes.OUTBOUND.getCode());
            List<CargoFileDO> receiptFileList = cargoFileMapper.selectList(receiptQuery);
            changeFiles(shipmentVO.getCargoId(), shipmentVO.getShipmentList(), receiptFileList, FileTypes.OUTBOUND.getCode());
        }

        //称重条照片
        {
            LambdaQueryWrapper<CargoFileDO> receiptQuery = Wrappers.lambdaQuery(CargoFileDO.class)
                    .eq(CargoFileDO::getCargoId, shipmentVO.getCargoId())
                    .eq(CargoFileDO::getFileType, FileTypes.WEIGHING_STRIP.getCode());
            List<CargoFileDO> receiptFileList = cargoFileMapper.selectList(receiptQuery);
            changeFiles(shipmentVO.getCargoId(), shipmentVO.getStripList(), receiptFileList, FileTypes.WEIGHING_STRIP.getCode());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addCustoms(CargoCustomsVO cargoCustomsVO){
        //报关信息
        {
//            LambdaQueryWrapper<CargoFileDO> receiptQuery = Wrappers.lambdaQuery(CargoFileDO.class)
//                    .eq(CargoFileDO::getCargoId, cargoCustomsVO.getCargoId())
//                    .eq(CargoFileDO::getFileType, FileTypes.CUSTOMS_INFOMATION.getCode());
//            List<CargoFileDO> receiptFileList = cargoFileMapper.selectList(receiptQuery);
//            List<Long> delList = Lists.newArrayList();
//            List<CargoFileDO> addList = Lists.newArrayList();
//            List<String> dataList = cargoCustomsVO.getCustomsList();
//            if(CollUtil.isNotEmpty(receiptFileList)){
//                Map<String, CargoFileDO> fileMap = receiptFileList.stream().collect(Collectors.toMap(CargoFileDO::getFileId, it->it));
//                if(CollUtil.isEmpty(cargoCustomsVO.getCustomsList())){
//                    delList = receiptFileList.stream().map(CargoFileDO::getId).collect(Collectors.toList());
//                }else{
//
//                    for(String key : fileMap.keySet()){
//                        if(!dataList.contains(key)){
//                            delList.add(fileMap.get(key).getId());
//                        }else{
//                            dataList.remove(key);
//                        }
//                    }
//                }
//            }
//            if(CollUtil.isNotEmpty(dataList)){
//                for(String fid : dataList){
//                    CargoFileDO fileDo = new CargoFileDO();
//                    fileDo.setCargoId(cargoCustomsVO.getCargoId());
//                    fileDo.setFileType(FileTypes.CUSTOMS_INFOMATION.getCode());
//                    fileDo.setFileId(fid);
//                    addList.add(fileDo);
//                }
//            }
//            if(CollUtil.isNotEmpty(delList)){
//                cargoFileMapper.deleteByIds(delList);
//            }
//            if(CollUtil.isNotEmpty(addList)){
//                cargoFileMapper.insertBatch(addList);
//            }
        }

        //其他资料
        {
//            LambdaQueryWrapper<CargoFileDO> receiptQuery = Wrappers.lambdaQuery(CargoFileDO.class)
//                    .eq(CargoFileDO::getCargoId, cargoCustomsVO.getCargoId())
//                    .eq(CargoFileDO::getFileType, FileTypes.FINISH_OTHERS.getCode());
//            List<CargoFileDO> receiptFileList = cargoFileMapper.selectList(receiptQuery);
//            List<Long> delList = Lists.newArrayList();
//            List<CargoFileDO> addList = Lists.newArrayList();
//            List<String> dataList = cargoCustomsVO.getOthersList();
//            if(CollUtil.isNotEmpty(receiptFileList)){
//                Map<String, CargoFileDO> fileMap = receiptFileList.stream().collect(Collectors.toMap(CargoFileDO::getFileId, it->it));
//                if(CollUtil.isEmpty(cargoCustomsVO.getOthersList())){
//                    delList = receiptFileList.stream().map(CargoFileDO::getId).collect(Collectors.toList());
//                }else{
//
//                    for(String key : fileMap.keySet()){
//                        if(!dataList.contains(key)){
//                            delList.add(fileMap.get(key).getId());
//                        }else{
//                            dataList.remove(key);
//                        }
//                    }
//                }
//            }
//            if(CollUtil.isNotEmpty(dataList)){
//                for(String fid : dataList){
//                    CargoFileDO fileDo = new CargoFileDO();
//                    fileDo.setCargoId(cargoCustomsVO.getCargoId());
//                    fileDo.setFileType(FileTypes.FINISH_OTHERS.getCode());
//                    fileDo.setFileId(fid);
//                    addList.add(fileDo);
//                }
//            }
//            if(CollUtil.isNotEmpty(delList)){
//                cargoFileMapper.deleteByIds(delList);
//            }
//            if(CollUtil.isNotEmpty(addList)){
//                cargoFileMapper.insertBatch(addList);
//            }
        }
    }

    @Override
    public Long createCargoFile(CargoFileSaveReqVO createReqVO) {
        // 插入
        CargoFileDO cargoFile = BeanUtils.toBean(createReqVO, CargoFileDO.class);
        cargoFileMapper.insert(cargoFile);
        // 返回
        return cargoFile.getId();
    }

    @Override
    public void updateCargoFile(CargoFileSaveReqVO updateReqVO) {
        // 校验存在
        validateCargoFileExists(updateReqVO.getId());
        // 更新
        CargoFileDO updateObj = BeanUtils.toBean(updateReqVO, CargoFileDO.class);
        cargoFileMapper.updateById(updateObj);
    }

    @Override
    public void deleteCargoFile(Long id) {
        // 校验存在
        validateCargoFileExists(id);
        // 删除
        cargoFileMapper.deleteById(id);
    }

    private void validateCargoFileExists(Long id) {
        if (cargoFileMapper.selectById(id) == null) {
            throw exception(CARGO_FILE_NOT_EXISTS);
        }
    }

    @Override
    public CargoFileDO getCargoFile(Long id) {
        return cargoFileMapper.selectById(id);
    }

    @Override
    public List<CargoFileDO> getCargoFileList(CargoFileReqVO pageReqVO) {
        return cargoFileMapper.selectList(pageReqVO);
    }

}